package com.ruoyi.system.ali;

import cn.hutool.core.date.DateUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import com.ruoyi.common.constant.ZfbAppIdConstants;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.enums.ChannelEnum;
import com.ruoyi.common.utils.BigDecimalUtil;
import com.ruoyi.common.utils.UrlHexUtil;
import com.ruoyi.common.utils.file.AliOss;
import com.ruoyi.common.utils.sign.SignMD5Util;
import com.ruoyi.system.biz.CashBizService;
import com.ruoyi.system.domain.Bank;
import com.ruoyi.system.domain.Order;
import com.ruoyi.system.domain.UserRate;
import com.ruoyi.system.dto.ApiByPhoneAddDto;
import com.ruoyi.system.service.*;
import com.ruoyi.system.vo.ApiPayResultVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.TreeMap;

/**
 * 支付宝转账
 */
@Component
@Slf4j
public class ZfbSmUidPayService implements ChannelService {
    @Resource
    ISysConfigService configService;
    private static final String serverUrl = "https://openapi.alipay.com/gateway.do";
    @Resource
    private ZfbConfigService zfbConfigService;
    @Resource
    private BankService bankService;
    @Resource
    private UserRateService userRateService;

    @Override
    public String getType() {
        return ChannelEnum.SM_UID.getCode();
    }

    @Resource
    private CashBizService cashService;

    @Resource
    private ISysUserService userService;
    @Resource
    private RedisCache redisCache;

    public Object create(AliPayDto aliPayDto, Order order) {
        Bank bank = bankService.getRand(order.getAmount(), this.getType());
        return create(order, bank);
    }

    @Override
    public Object createByPhone(ApiByPhoneAddDto apiByPhoneAddDto, Order order) {
        Bank bank = bankService.getUserBank(order.getUserId(), order.getAmount(), this.getType());
        return create(order, bank);
    }

    //uid
    public Object create(Order order, Bank bank) {
        BigDecimal amount = order.getAmount();
        order.setAmount(BigDecimalUtil.setDecimal(amount));

        //冻结收款用户的金额
//        CashHistory userCashHis = new CashHistory(bank.getUserId(), order.getAmount(), "reduce", "代收订单", "freeze");
//        userCashHis.setOrderNo(order.getOrderNo());
//        cashService.updateCash(userCashHis);
        order.setChannelCode(this.getType());
        order.setChannelName(ChannelEnum.getName(this.getType()));
        order.setAccount(bank.getCardNo());
        order.setName(bank.getName());
        order.setType("hand");
        order.setBankName("支付宝");
        order.setUserId(bank.getUserId());
        //SysUser sysUser = userService.check(bank.getUserId());
        UserRate userRate = userRateService.checkUserRate(bank.getUserId(), this.getType());
        order.setEarning(order.getAmount().multiply(userRate.getRate().divide(new BigDecimal(100))));
        order.setUsername(bank.getUsername());
        order.setZfbUserId(bank.getZfbUserId());

        ApiPayResultVo apiVo = new ApiPayResultVo();
        apiVo.setAmount(String.valueOf(order.getAmount()));
        apiVo.setOrderNo(order.getOrderNo());
        apiVo.setMerchantId(order.getMerchantId());
        TreeMap<String, String> map = SignMD5Util.objToMap(apiVo);
        map.put("payType", "6");
        String sign = SignMD5Util.getSign(map, "sign");
        String payUrl = configService.selectConfigByKey("template");
        payUrl = payUrl + "?" + SignMD5Util.getStr(map, sign);
        apiVo.setUrl(payUrl);

        try {
            //将链接解析成二维码
            String remark = "";
            if (order.getAmount().compareTo(new BigDecimal(500)) >= 0) {
                remark = DateUtil.month(new Date()) + "月房租";
            } else {
                remark = "个人转账";
            }
            remark= UrlHexUtil.encode(remark);
            BigDecimal bigDecimal = BigDecimalUtil.getNumber(apiVo.getAmount());
          //  String url = "https://ds.alipay.com/?from=m&appId=" + ZfbAppIdConstants.zhAppid + "&actionType=toAccount&goBack=NO&amount=" + bigDecimal + "&userId=" + bank.getZfbUserId() + "&memo=" + remark;
String url="https://render.alipay.com/p/s/i?scheme=alipay%3A%2F%2Fplatformapi%2Fstartapp%3FsaId%3D20000116%26actionType%3DtoAccount%26goBack%3DNO%26amount%3D"+bigDecimal+"%26userId%3D"+bank.getZfbUserId()+"%26memo%3D"+remark;

            QrConfig qrConfig = new QrConfig();
            qrConfig.setWidth(200);
            qrConfig.setHeight(200);
            byte[] bytes = QrCodeUtil.generatePng(url, qrConfig);
            String projectName = configService.selectConfigByKey("projectName");
            String picUrl = AliOss.uploadToOss(bytes, projectName + "/orderReceive/" + apiVo.getOrderNo() + ".jpg");
            String encode = UrlHexUtil.encode(url);
            //跳转url
            url="alipays://platformapi/startapp?saId=10000007&qrcode="+encode;
            order.setZfbUrl(url);
            order.setHtml(picUrl);
            order.setPic(picUrl);
        } catch (Exception e) {
            log.info("支付宝转账转二维码失败:{}", e.getMessage());
        }

        return apiVo;
    }


}
